<template>
  <div class="w-[100%] h-[100%] flex">
    <div class="left w-[938px]">
      <el-button size="large" class="w-[80px]"         @click="handleBtnClick({type:'back'})">
        <div class="w-[12px] h-[12px] bg mr-[5px]"

             style="background-image: url(https://img.alicdn.com/imgextra/i3/801089336/O1CN01esxE5R2IpwkB2inWV_!!801089336.png)"></div>
        返回
      </el-button>

      <div class="mt-[30px] text-[20px]">
        余额充值
      </div>

      <div class="mt-[30px] flex">
        <div class="text-[#666666] mr-[40px]">账户ID:viviweiomilad</div>
        <div class="text-[#666666]">当前可用余额：￥{{ countInfo.balance }}</div>
      </div>

      <div class="flex items-center mt-[20px]" v-style="`gap:10px`">
        充值金额：
        <el-input class="w-[280px]" v-style="'width:280px'" v-model="money" type="number"/>
        <el-button type="primary" class="w-[74px]" color="#3721FF"
                   @click="handleBtnClick({type:'confirm'})">确认
        </el-button>
      </div>

      <div class="mt-[20px] flex flex-wrap" v-style="`gap:20px;`">
        <div v-for="(item,index) in config" :key="index"
             class="w-[226px] h-[143px] bg px-[16px] py-[16px] relative transition"
             @click="handleBtnClick({type:'money',index,item})"
             :style="`background-image: url(${ active == index ? 'https://img.alicdn.com/imgextra/i1/801089336/O1CN01FT44Iw2IpwkAlNBMm_!!801089336.png' : 'https://img.alicdn.com/imgextra/i1/801089336/O1CN01VcyEEO2IpwkBK04px_!!801089336.png' })`"
        >

          <!--          <div class="flex">-->
          <!--            <div class="text-[#fff] h-[18px] px-[10px] badget text-[10px] rounded-[3px]">-->
          <!--              5折{{ item.value }}-->
          <!--            </div>-->

          <!--          </div>-->

          <div class="mt-[20px] flex-center" style="align-items: flex-end;">
            <div :style="`${ index == active ? `color:#3721FF` : '' }`"
                 class="text-[22px] mb-[-3px] mr-[5px]">
              {{ item.value }}
            </div>
            <div :style="`${ index == active ? `color:#3721FF` : '' }`">元</div>
          </div>


          <div
            class="w-[100%] h-[38px] bg-[rgba(255,136,0,0.06)] absolute bottom-[0] left-[0] pl-[45px] flex items-center text-[#FF731A]"
            v-style="`border-radius:0 0 10px 10px`">
            <!--            省了200元-->
          </div>


        </div>
      </div>

      <div class="mt-[63px] w-[659px] h-[104px] bg"
           style="background-image: url(https://img.alicdn.com/imgextra/i1/801089336/O1CN01xd7y2S2IpwkB3yoae_!!801089336.png)">

      </div>

    </div>

    <div class="right flex-center h-[100%]" v-if="isShowBarCode">
      <div>
        <div style="border:  solid 1px #F5F5F5" class="px-[20px] py-[20px]">

          <div class="mb-[20px] flex-center">
            <el-radio-group v-model="selectedMethod" @change="onChange">

              <el-radio :value="item.code"
                        v-for="(item,index) in method"
                        :key="index"
              >
                <div class="w-[30px] h-[30px] bg" :style="`background-image:url(${ item.url })`">

                </div>
              </el-radio>

            </el-radio-group>
          </div>


          <div class="w-[240px] h-[240px] barCodeContainer">
            <canvas :id="ctxId" v-style="`width: 100%;height:100%;`" class=""
            >

            </canvas>
          </div>

        </div>

        <div class="mt-[40px] flex-center">应付金额：<span
          class="text-[22px] text-[#FF4E00]">￥{{ money }}</span></div>

      </div>
    </div>
  </div>
</template>
<script setup lang="ts">

import {FeeApi} from "@/api/fee";
import router from "@/router";
import {throttle} from "@/utils";
import dayjs from "dayjs";
import {useAppStore} from "@/store/modules/app";

const app = useAppStore();


import {DICT_TYPE, getStrDictOptions} from "@/utils/dict";
import QRCode from "qrcode";

const payType = getStrDictOptions(DICT_TYPE.PAY_TYPE);
const businessType = getStrDictOptions(DICT_TYPE.BUSINESS_TYPE);

const orderInfo = ref({})
const submitInfo = ref({})

const ctxId = ref(`ctx${+new Date()}`)
const config = ref([
  {
    value: "66.66"
  },
  {
    value: "88.88",
    less: 200
  },
  {
    value: "99.99"
  },
  {
    value: "168.88",
    less: 200
  },
  {
    value: "666.66",
    less: 200
  }
])

const active = ref(-1);

const isShowBarCode = ref(false)

const money = ref(0)


const method = ref([
  {
    name: "微信",
    url: "https://img.alicdn.com/imgextra/i3/801089336/O1CN01uLMQLc2IpwkBoslCg_!!801089336.png",
    code: "wechat",
    code1: "wx_native"
  },
  {
    name: "支付宝",
    url: "https://img.alicdn.com/imgextra/i2/801089336/O1CN01PqY72i2Ipwk56JFFD_!!801089336.png",
    code: "alipay",
    code1: "alipay_qr"
  }
])

const selectedMethod = ref("wechat")

const countInfo = ref({})

const handleBtnClick = e => {
  let type = e.type;
  try {
    fn[type](e)
  } catch (e) {
    console.log(`${type}不存在`)
  }
}

const fn = {
  money({index, item}) {
    active.value = index;
    money.value = item.value
  },
  back() {
    console.log("???")
    router.go(-1)
  },
  confirm: throttle(async () => {
    //类型1.流量 ，2.充值金额，3.席位，4.短信，5.物流,6.套餐

    let res = await FeeApi.generateOrder1({
      payPrice: 1,// Math.round(( money.value || 0) * 100),
    })
    orderInfo.value = res;
    isShowBarCode.value = true;

    //生成二维码
    getBarCode();

  }, 1000)
}

const getBarCode = async () => {
  let res = await FeeApi.submitOrder({
    channelCode: method.value.find(at => at.code == selectedMethod.value)?.code1,
    returnUrl: "https://blog.csdn.net/xiao_qiang666/article/details/148592009",
    id: orderInfo.value.payOrderId,
    displayMode: "qr_code",
    channelExtras: orderInfo.value
  })

  submitInfo.value = res;
  nextTick(() => {
    initCanvas();
  })
}


const initCanvas = () => {
  const canvas = document.getElementById(ctxId.value);

  let dom = document.querySelector('.barCodeContainer');

  QRCode.toCanvas(
    canvas,
    submitInfo.value.displayContent || '',//props.content,
    {
      scale: 4, // 二维码的每个点的像素大小
      width: dom.offsetWidth, // 在浏览器中显示的宽度
      margin: 1 // 二维码周围的空白边距
    }
  );

};


const initPromise = async () => {
  let res = await Promise.all([FeeApi.getBalance()])
  let balance = res[0].balance || 0;
  balance = Math.round(balance)/100
  countInfo.value = {
    ...res[0],
    balance:balance.toString()
  }

}

const onChange=()=>{
  fn.confirm();
}

onMounted(() => {
  initPromise();
})

watch(() => [money.value], () => {
  isShowBarCode.value = false;
}, {
  immediate: true
})

// watch(() => [selectedMethod.value], () => {
//   console.log("??????")
//   fn.confirm();
// }, {
//   immediate: true
// })


const generateInfo=()=>{
  let option = {
    orderInfo: orderInfo.value,
    selectedPackage:{
     // packageCount:seatInfo.value.dataValue,
      discountPrice:money.value,
      //...props.selectedPackage,
      time:dayjs( submitInfo.value.successTime).format('YYYY-MM-DD HH:mm:ss'),
      type:3,
      method:method.value.find(at => at.code == selectedMethod.value)?.name,
    }
  }

  return option
}




watch(() => app.payStatus, () => {
  if (app.payStatus) {
    sessionStorage.setItem('payInfo', JSON.stringify(generateInfo()))
    app.payStatus = false;
    router.push(`/fee/fee/paid`);
  }
}, {
  immediate: true
})


</script>
<style lang="scss" scoped>
.badget {
  background: linear-gradient(to right, #ff6212, #ffb74f);
}
</style>
